﻿using System;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Jy.Abp.Settings;
using Volo.Abp.Settings;

namespace Jy.Abp.SettingManagement;

public static class TenantTypedSettingsManagerExtensions
{
    public static Task<TSettings> GetForTenantAsync<TSettings>(this ITypedSettingsManager settingManager, [NotNull] string name, Guid tenantId, bool fallback = true)
        where TSettings : ITypedSettings
    {
        return settingManager.GetAsync<TSettings>(TenantSettingValueProvider.ProviderName, tenantId.ToString(), fallback);
    }

    public static Task<TSettings> GetForCurrentTenantAsync<TSettings>(this ITypedSettingsManager settingManager, [NotNull] string name, bool fallback = true)
        where TSettings : ITypedSettings
    {
        return settingManager.GetAsync<TSettings>(TenantSettingValueProvider.ProviderName, null, fallback);
    }

    public static Task SetForTenantAsync<TSettings>(this ITypedSettingsManager settingManager, Guid tenantId, [NotNull] TSettings settings, bool forceToSet = false)
        where TSettings : ITypedSettings
    {
        return settingManager.SetAsync(settings, TenantSettingValueProvider.ProviderName, tenantId.ToString(), forceToSet);
    }

    public static Task SetForCurrentTenantAsync<TSettings>(this ITypedSettingsManager settingManager, [NotNull] TSettings settings, bool forceToSet = false)
        where TSettings : ITypedSettings
    {
        return settingManager.SetAsync(settings, TenantSettingValueProvider.ProviderName, null, forceToSet);
    }

    public static Task SetForTenantOrGlobalAsync<TSettings>(this ITypedSettingsManager settingManager, Guid? tenantId, [NotNull] TSettings settings, bool forceToSet = false)
        where TSettings : ITypedSettings
    {
        if (tenantId.HasValue)
        {
            return settingManager.SetForTenantAsync(tenantId.Value, settings, forceToSet);
        }

        return settingManager.SetGlobalAsync(settings);
    }
}
